/*
 * Esta clase requiere del valor ModuleName almacenado en el logged
 * para localizar el archivo correspondiente a los mensajes
 */
package system.general;

import java.util.ResourceBundle;
import javax.annotation.ManagedBean;
import javax.el.ELContext;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author avbravo
 */
@ManagedBean
@RequestScoped
public class Message {

    Logged logged;
    private ResourceBundle rb;
    private String namePackage = "";

    public Message() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    private void loadBundle() {
        String idiom = "es";
        if (!logged.getLoggedIdiom().toLowerCase().equals("")) {
            idiom = logged.getLoggedIdiom().toLowerCase();
        }
        rb = ResourceBundle.getBundle(namePackage + ".message_" + idiom);
    }

    public void showMsg(String namePackage, String title, String code) {
        this.namePackage = namePackage;
        loadBundle();
        title = rb.getString(title);
        String msg = rb.getString(code);

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, title, msg);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public void showErr(String namePackage, String title, Exception ex) {
        this.namePackage = namePackage;
        loadBundle();
        title = rb.getString(title);
        String msg = (String) ex.getMessage();

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, title, msg);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public static String getRequestParameter(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key);
    }

    public static Object getObjectFromRequestParameter(String requestParameterName, Converter converter, UIComponent component) {
        String theId = Message.getRequestParameter(requestParameterName);
        return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId);
    }
}
